package com.hbzjt2012.array;

public class ArrayDemo07 {
    public static void main(String[] args) {
        //1.创建一个二维数组11*11 0：没有棋子  1：黑棋  2：白棋
        int[][] array = new int[11][11];
        array[1][2] = 1;
        array[2][3] = 2;

        //输出原始的数组
        System.out.println("输出原始的数组为：");

        for (int[] ints : array) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }

        System.out.println("==========================================");
        
        //转换为稀疏数组来保存
        //获取有效值的个数
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                if(array[i][j] != 0){
                    sum++;
                }
            }
        }
        System.out.println("有效值的个数为：" + sum);

        //2.创建一个稀疏数组的数组
        int[][] newArray = new int[sum + 1][3];
        newArray[0][0] = 11;
        newArray[0][1] = 11;
        newArray[0][2] = sum;

        //遍历二维数组，将非零的值，存放在稀疏数组中
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if(array[i][j] != 0){
                    count++;
                    newArray[count][0] = i;
                    newArray[count][1] = j;
                    newArray[count][2] = array[i][j];
                }
            }
        }

        //输出稀疏数组
        System.out.println("稀疏数组为：");

        for (int i = 0; i < newArray.length; i++) {
            System.out.println(newArray[i][0] + "\t" + newArray[i][1] + "\t" + newArray[i][2] + "\t");
        }

        System.out.println("==========================================");
        System.out.println("还原后的数组为：");

        //1.读取稀疏数组的值
        int[][] array1 = new int[newArray[0][0]][newArray[0][1]];

        //2.给其中的元素还原它的值
        for (int i = 1; i < newArray.length; i++) {
            array1[newArray[i][0]][newArray[i][1]] = newArray[i][2];
        }

        //3.打印
        for (int[] ints : array1) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
    }
}
